package com.juyu.miliao.api.service;

import com.juyu.miliao.api.dao.mysql.BillDetailDao;
import com.juyu.miliao.api.dao.mysql.UserInfoDao;
import com.juyu.miliao.api.dao.mysql.UserWalletDao;
import com.juyu.miliao.api.dao.redis.UserRedisDao;
import com.juyu.miliao.api.domain.Appkey;
import com.juyu.miliao.api.domain.BillDetail;
import com.juyu.miliao.api.domain.User;
import com.juyu.miliao.api.domain.UserWallet;
import com.juyu.miliao.api.exception.WrongNoDepositException;
import com.juyu.miliao.common.util.DoubleFormatUtil;
import com.juyu.miliao.api.util.FileUtil;
import com.juyu.miliao.common.constant.RecordTypeEnum;
import com.juyu.miliao.common.domain.CommonHead;
import com.juyu.miliao.common.exception.ConsumeRuntimeException;
import com.juyu.miliao.common.util.VerifyUtil;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 聊天service
 * @Auther: 卜加超
 * @Date: 2019/3/12 19:54
 * @Description:
 */
@Service
@Slf4j
public class UserChatService {
    @Resource
    private UserInfoDao userInfoDao;
    @Resource
    private UserRedisDao userRedisDao;
    @Resource
    private UserWalletDao userWalletDao;
    @Resource
    private AppKeyService appkeyService;
    @Resource
    private BillDetailDao billDetailDao;

    @Value("${logging.path}")
    private String classPath;

    /**
     *
     * @param outId 发起方:用户
     * @param insertId 接收方:主播
     * @return
     */
    public JSONObject getUserChat(long outId, long insertId) {
        JSONObject jsonObject = new JSONObject();
        //判断接入方是否是主播
        User insertUser= userInfoDao.getUserById(insertId);
        User outUser = userInfoDao.getUserById(outId);

        //用户和主播聊天
        if(outUser.getIsHost()==2&&insertUser.getIsHost()==1){
            if(outUser.getIsVip()==1 || outUser.getIsSvip()==1 || outUser.getIsPlatinumVip()==1){
                jsonObject.put("isChat",true);
                jsonObject.put("isVip",outUser.getIsVip());
                double num = userRedisDao.addUserChat(outUser.getUserId(), insertId, 1);
                jsonObject.put("num",num);
            }else{
                //聊天次数
            jsonObject = chatCout(outUser, insertId);

            }
            //主播发起的聊天免费
        }else if(outUser.getIsHost()==1){
            jsonObject.put("isChat",true);
            jsonObject.put("isVip",outUser.getIsVip());
            jsonObject.put("num",1);
            //用户和用户聊天
        } else {
            if(outUser.getIsVip()==1 || outUser.getIsPlatinumVip()==1 || outUser.getIsSvip()==1){
                jsonObject.put("isChat",true);
                jsonObject.put("isVip",outUser.getIsVip());
                jsonObject.put("num",1);
            }else{
                //聊天次数
                jsonObject = chatCout(outUser, insertId);
            }
        }
        return jsonObject;
    }

    /***
     * 用户聊天消费实现
     * 用户免费聊天3句之后每次说话扣1金币
     * @param outId 发起方:用户
     * @param insertId 接收方:主播
     */
    public void getUserTollChat(long outId, long insertId,HttpServletRequest request) {
        Double userChatScore = userRedisDao.getUserChat(outId,insertId);
        if(userChatScore==null || userChatScore<3){
            throw new ConsumeRuntimeException("免费次数未到");
        }
        User outUser = userInfoDao.getUserById(outId);
        User insertUser = userInfoDao.getUserById(insertId);

        if(outUser.getIsHost()==2&&insertUser.getIsHost()==1){
            hostTolChat(outUser,insertUser);
        }else if(outUser.getIsHost()==2&&insertUser.getIsHost()==2) {
            tollChat(outUser,insertUser,request);
        }if(outUser.getIsHost()==1){
            throw new ConsumeRuntimeException("主播发起聊天不收费");
        }
    }

    //用户与用户聊天扣费方法 （接收方为用户 用户消费金币为平台所有）
    public void tollChat(User outUser,User insertUser,HttpServletRequest request) {
        if (outUser.getIsVip() != 1 && outUser.getIsSvip()!=1 && outUser.getIsPlatinumVip()!=1) {
            UserWallet outUserWallet = new UserWallet();
            outUserWallet.setUserId(outUser.getUserId());
            //用户扣费1金币
            outUserWallet.setDeposit(1);
            int num = userWalletDao.minusDeposit(outUserWallet);
            if (num != 1) {
                throw new WrongNoDepositException("金币不足");
            }
            CommonHead com = VerifyUtil.verifyCommonHead(request);
            Date date = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String content ="手机系统phoneSystem："+com.getPhoneSystem()+",版本versionNum:"+com.getVersionNum()+",渠道channel:"+com.getChannel()
                    +",应用Id(appPackageId):"+com.getAppPackageId()+"，线上线下来源(0-线下 1-线上)online："+com.getOnline()+"的用户："
                    + outUser.getUserId()+ "与"+insertUser.getUserId()+"在"+simpleDateFormat.format(date)+"聊天，"
                    +"ID：" + outUser.getUserId() + "的用户：" + outUser.getNickName()
                    + ":本次消费了1金币";
            String filePath = classPath + "userChat.txt";
            FileUtil.writeToTxtFile(content, filePath);
        }
    }

    //用户和主播聊天扣费（接收方为主播 用户消费金币为主播所有）
    public void hostTolChat(User outUser, User insertUser) {
        if (outUser.getIsVip() != 1  && outUser.getIsSvip()!=1 && outUser.getIsPlatinumVip()!=1) {
            UserWallet outUserWallet = new UserWallet();
            outUserWallet.setUserId(outUser.getUserId());
            //用户扣费1金币
            outUserWallet.setDeposit(1);
            int num = userWalletDao.minusDeposit(outUserWallet);
            if (num != 1) {
                throw new WrongNoDepositException("金币不足");
            }
            // 获取金币兑换钻石比例
            Appkey appkey = appkeyService.getAppKeyByKey("giftRatio");
            // 金币转换钻石
            double diamond = DoubleFormatUtil.doubleFormate(1 * Double.parseDouble(appkey.getValue()));
            //保存消费记录
            BillDetail billDetail = new BillDetail();
            billDetail.setRecordType(RecordTypeEnum.USER_CHAT.state);// 消费类型19 聊天消费
            billDetail.setInUserId(insertUser.getUserId());// 赚取钻石用户id
            billDetail.setOutUserId(outUser.getUserId());// 消费金币用户id
            billDetail.setDiamond(diamond);// 赚取钻石数
            billDetail.setSpend(outUserWallet.getDeposit());// 消费金币数
            billDetailDao.insertBillDetail(billDetail);
            //主播聊天加相应的钻石
            UserWallet inUserWallet = userWalletDao.getUserWalletById(insertUser.getUserId());
            inUserWallet.setDiamond(diamond);
            userWalletDao.reviseDiamond(inUserWallet);
        }
    }
    //聊天次数方法
    public JSONObject chatCout(User outUser, long insertId) {
        JSONObject jsonObject = new JSONObject();
        Double userChatScore = userRedisDao.getUserChat(outUser.getUserId(),insertId);
        //如果第一次链接记录次数
        if( userChatScore== null){
            double num = userRedisDao.addUserChat(outUser.getUserId(), insertId, 1);
            jsonObject.put("isChat",true);
            jsonObject.put("num",num);
        }else if (userChatScore < 3) {
            //记录过次数每次调用次数加1
            double num = userRedisDao.addUserChat(outUser.getUserId(), insertId, 1);
            jsonObject.put("isChat",true);
            jsonObject.put("num",num);
        }else{
            jsonObject.put("isChat",false);
            jsonObject.put("num",userChatScore+1);
        }
        jsonObject.put("isVip",outUser.getIsVip());

        return jsonObject;
    }
}
